//
//  ThirdViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/9/17.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import SVProgressHUD
import Eureka
import SnapKit
import SwiftyUserDefaults


class ThirdViewController: BaseViewController ,UITableViewDataSource,UITableViewDelegate
{
    var titleArr0 = [String]()
    var titleArr1 = [String]()
    var myuserModel = userModel()
    
    lazy var nameLaebl : UILabel = {
        let nameLaebl = UILabel()
        return nameLaebl
    }()
    
    lazy var phoneLabel : UILabel = {
        let phoneLabel = UILabel()
        return phoneLabel
    }()
    lazy var topphoto : UIImageView = {
        let topphoto = UIImageView()
        return topphoto
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        makeBaseUI()
        
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(_ animated: Bool) {
        layoutNav()
        getData()
    }
    
    //MARK: - Private methods
    
    
    func getData() {
        
        MyNetwork.request(target: .userinfo(user_id: Defaults[.userID]!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
               
                self.myuserModel.yy_modelSet(withJSON:(result as AnyObject)["data"]);
                self.myTableView.reloadData()
                Defaults[.qrCodeUrl] = self.myuserModel.qrCodeUrl
                Defaults[.check_Type] = "2"
//                Defaults[.check_Type] = self.myuserModel.check_type
            }else{
//                self.navigationController?.view.makeToast(needModel.message)
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    func makeBaseUI(){
        self.view.addSubview(myTableView)
        //XALanguageManager.getString(key: "货币")
        titleArr0 = [XALanguageManager.getString(key: "语言"),XALanguageManager.getString(key: "我的邀请码"),XALanguageManager.getString(key: "谷歌账户验证")]
        titleArr1 = [XALanguageManager.getString(key: "关于我们"),XALanguageManager.getString(key: "联系我们")]
    }
    
    
    
    
    
    @objc func changeLanguage(){
        if (UserDefaults.standard.value(forKey: "langeuage") as! String) == "en"{ // 英语
             tabBarController?.title = XALanguageManager.getString(key: "设置")
        } else {
            
        }
    }
    func layoutNav(){
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        tabBarController?.title =  XALanguageManager.getString(key: "设置")
        
        self.navigationController?.isNavigationBarHidden = false
        //navigationController?.navigationBar.subviews[0].removeFromSuperview()//去掉NavigationBar的背景和横线
    }


    //MARK: - tableView Delegate And DataSource
   
    
    override func willMove(toParentViewController parent: UIViewController?) {
        
    }
    
    
    //MARK: - tableView Delegate And DataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let reuseIdentifier = "staticCellReuseIdentifier - \(indexPath.description)"
        
        var cell:SettingTableViewCell! = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)as?SettingTableViewCell
        if cell == nil {
            cell = SettingTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: reuseIdentifier)
            cell.selectedBackgroundView = UIView(frame: cell.frame);
            cell.selectedBackgroundView?.backgroundColor = UIColor("#070E33")
        }
        cell.LineView.backgroundColor = UIColor("#293163")
        cell.backgroundColor = UIColor.clear
        cell.accessoryType = .disclosureIndicator
        if indexPath.section == 1 {
            
            cell?.titleLab?.text = XALanguageManager.getString(key: "钱包")
        }
        cell.titleLab?.textColor = UIColor.white
        cell.priceLab?.textColor = UIColor.white
        if indexPath.section == 2 {
            cell?.titleLab?.text = titleArr0[indexPath.row]
            if indexPath.row == 10{
                cell.priceLab?.textColor = UIColor("909090")
                cell.priceLab?.text = "DKE"
            }else if indexPath.row == 0{
                cell.priceLab?.textColor = UIColor("909090")
                cell.priceLab?.text = XALanguageManager.getString(key: "语种")
            }else if indexPath.row == 1{
                cell.priceLab?.textColor = UIColor("#418DFF")
                cell.priceLab?.text = Defaults[.vip_code]
            }else{
                cell.priceLab?.textColor = UIColor("#418DFF")
                cell.priceLab?.text = ""
            }

        }else if indexPath.section == 3{
            cell.titleLab?.text = titleArr1[indexPath.row]
            cell.priceLab?.text = ""
        }else if indexPath.section == 4 {
            cell.LineView.backgroundColor = UIColor.clear
            cell.accessoryType = .none
            cell.selectionStyle = .none
            cell.titleLab?.text = XALanguageManager.getString(key: "111")
            cell.titleLab?.textColor = UIColor.clear
        }
        else if indexPath.section == 5 {
            cell.LineView.backgroundColor = UIColor.clear
            cell.titleLab?.text = XALanguageManager.getString(key: "退出")
           
           cell.titleLab?.backgroundColor = UIColor("#323361")
            cell.titleLab?.clipsToBounds = true
            cell.titleLab?.layer.cornerRadius = 20
            cell.selectionStyle = .none
        cell.contentView.layer.cornerRadius = 20
            cell.titleLab?.textAlignment = .center
            cell.accessoryType = .none
        }else if indexPath.section == 0 {
            cell.LineView.backgroundColor = UIColor.clear
            
            cell.accessoryType = .none
            topphoto.layer.cornerRadius = 23;
            cell.contentView.addSubview(topphoto)
            topphoto.snp.makeConstraints { (make) in
            make.centerX.equalTo(cell)
                make.size.equalTo(CGSize(width: 46, height: 46))
                make.top.equalTo(26)
            }
            var url1:URL
            if self.myuserModel.avatar == nil{
                url1 = URL( string:String(format: "http://renedescartes.io"))!
            }else{
                url1 = URL( string:String(format: "http://renedescartes.io%@", self.myuserModel.avatar!))!
            }
            
            topphoto.sd_setImage(with: url1, placeholderImage: UIImage.init(named: "修改个人头像"), options: [], progress: nil, completed:nil)
            
            topphoto.clipsToBounds = true
            
            
            nameLaebl.textAlignment = .center
            cell.contentView.addSubview(nameLaebl);
            nameLaebl.snp.makeConstraints { (make) in
                make.top.equalTo(topphoto.snp.bottom).offset(5)
                make.size.equalTo(CGSize(width: 200, height: 16))
                make.centerX.equalTo(cell.contentView)
            }
            nameLaebl.textAlignment = .center
            nameLaebl.font = UIFont.systemFont(ofSize: 15)
            
            if self.myuserModel.nick_name == nil || self.myuserModel.nick_name == ""{
                nameLaebl.text = XALanguageManager.getString(key: "昵称")
                self.myuserModel.nick_name = XALanguageManager.getString(key: "昵称")
            }else{
                nameLaebl.text = self.myuserModel.nick_name
            }
            let attrMStr = NSMutableAttributedString()
            let attacmentM_baozhi = NSTextAttachment()
            attacmentM_baozhi.image = UIImage(named: "编辑@2x")
            attacmentM_baozhi.bounds = CGRect(x: 5, y: 0, width: 12, height: 12)
            
            var attrMStrbaozhi : NSAttributedString = NSAttributedString(string: self.myuserModel.nick_name!)
            attrMStrbaozhi = NSAttributedString(string: String(format:"%@",self.myuserModel.nick_name!))
            
            let attacmentM_baozhi2 = NSAttributedString(attachment: attacmentM_baozhi)
            attrMStr.append(attrMStrbaozhi)
            attrMStr.append(attacmentM_baozhi2)

            nameLaebl.attributedText = attrMStr
            
            nameLaebl.textColor = UIColor.white
            
            
            
            phoneLabel.textAlignment = .center
            phoneLabel.textColor = UIColor.white
            cell.contentView.addSubview(phoneLabel);
            phoneLabel.snp.makeConstraints { (make) in
                make.top.equalTo(nameLaebl.snp.bottom).offset(5)
                make.size.equalTo(CGSize(width: 200, height: 16))
                make.centerX.equalTo(cell.contentView)
            }
            phoneLabel.textColor = UIColor("909090")
            phoneLabel.textAlignment = .center
            phoneLabel.font = UIFont.systemFont(ofSize: 15)
            if myuserModel.mobile == nil{
                phoneLabel.text = ""
            }else{
                let str =  String(format:  "%@",myuserModel.mobile!)
//                let index = str.index(str.startIndex, offsetBy: 3)
//                let endex = str.index(str.startIndex, offsetBy: 9)
//                phoneLabel.text = String(format:"%@******%@",str.prefix(upTo: index) as CVarArg,str.suffix(from: endex) as CVarArg)
            }
        }
        return cell
    }
    
    //footer height
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    // row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 120
        }
        if indexPath.section == 5 {
            return 80
        }
        return 45
    }
    // header height
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    // row num
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }else if section == 2{
            return titleArr0.count
        }else if section == 3{
            return titleArr1.count
        }else{
            return 1
        }
        
    }
    // 组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 6
    }
    
    //点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        var tableViewCell = SettingTableViewCell()
        tableViewCell = myTableView.cellForRow(at: indexPath) as! SettingTableViewCell

        if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "语言"){
            self.navigationController?.pushViewController(LanguageViewController(), animated: true)
            return
        }
        
        if Defaults[.isLogInKey] == false{
            super.LogIn()
            return
        }
        
        if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "货币"){
            
            
        }else if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "我的邀请码"){
           let codVC = TowCodeViewController()
            codVC.myCode = "url"
            self.navigationController?.pushViewController(codVC, animated: true)
            
            
        }else if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "谷歌账户验证"){
            let codVC = googleCodeViewController()
            codVC.myCode = self.myuserModel.qrCodeUrl
            self.navigationController?.pushViewController(codVC, animated: true)
            
            
        }
        else if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "语言"){
            self.navigationController?.pushViewController(LanguageViewController(), animated: true)
        }else if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "关于我们"){
            let MyWebVC = MyBaseWebViewController()
            MyWebVC.title = XALanguageManager.getString(key: "关于我们");
            
            if XALanguageManager.getString(key: "语种") == "English" {
                MyWebVC.urlStr = "http://renedescartes.io/web/home/aboutuse"
            }else if XALanguageManager.getString(key: "语种") == "繁體中文"{
                MyWebVC.urlStr = "http://renedescartes.io/web/home/aboutusf"
            }else{
                MyWebVC.urlStr = "http://renedescartes.io/web/home/aboutus"
            }
            
            
            self.navigationController?.pushViewController(MyWebVC, animated: true)
            
            
        }else if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "联系我们"){
            
//            UIApplication.shared.openURL(NSURL.init(string: "tel://400-8888-9999")! as URL)
            let alertVC : UIAlertController = UIAlertController.init(title: "support@dkecoin.io", message: "", preferredStyle: .alert)

            let falseAA : UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)

            let trueAA : UIAlertAction = UIAlertAction.init(title: "Copy", style: .default) { (alertAction) in
                    UIPasteboard.general.string = "support@renedescartes.io"
                    
                    SVProgressHUD.showSuccess(withStatus: XALanguageManager.getString(key: "复制成功"))
                    SVProgressHUD.dismiss(withDelay: 0.5)
                    
                    
                    
                

            }

//            alertVC.addAction(falseAA)

            alertVC.addAction(trueAA)

            self.present(alertVC, animated: true, completion: nil)
            
        }else if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "退出"){
            
            
            
            let alertController = UIAlertController(title:XALanguageManager.getString(key: "系统提示") ,
                                                    message: XALanguageManager.getString(key: "您确定要退出吗？"), preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: XALanguageManager.getString(key: "取消"), style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: XALanguageManager.getString(key: "确定"), style: .default, handler: {
                action in
                Defaults.removeAll();
                self.getData();
                
                self.topphoto.image = UIImage.init(named: "修改个人头像")
                
                
                self.myuserModel.mobile = nil
                self.myuserModel.avatar = nil
                self.myuserModel.nick_name = XALanguageManager.getString(key: "昵称")
                
                self.myTableView.reloadData()
                
//                topphoto.sd_setImage(with: url1, placeholderImage: UIImage.init(named: "修改个人头像"), options: [], progress: nil, completed:nil)
                
                //Defaults[.isLogInKey] = flase

                print("点击了确定")
            })
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
            
        }else if tableViewCell.titleLab?.text == XALanguageManager.getString(key: "钱包"){
            if Defaults[.content] == ""{
                self.navigationController?.pushViewController(walletViewController(), animated: true)
            }else{
                self.navigationController?.pushViewController(AddressDetailViewController(), animated: true)
            }
            
        }else{
            if indexPath.section == 0{
                self.navigationController?.pushViewController(ProfileViewController(), animated: true)
            }
             
        }
        
        
    }
    
    
    // MARK: - 懒加载
    private lazy var myTableView:UITableView = {
        
            var tempheight = CGFloat()
            tempheight = 64
            if #available(iOS 11.0.0, *) {
                tempheight = 0
                print("iOS 9.3.5 is available")
            }
        let myTableView = UITableView(frame: CGRect(x: 0, y: tempheight, width: kScreenWidth, height: kScreenHeight - tempheight - 49), style: UITableViewStyle.grouped)
        myTableView.delegate = self
        myTableView.dataSource = self
        myTableView.backgroundColor = UIColor.clear
        myTableView.separatorStyle = .none;
        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        myTableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
        myTableView.backgroundColor = UIColor.clear
        
        return myTableView
    }()
   
   
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
